package com.wondertek.poms.core.service.impl;

import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.ICpInfoService;
import com.wondertek.poms.dao.po.CpInfo;
import com.wondertek.poms.dao.repo.ICpInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenjijiang
 * @description
 */
@Service
public class CpInfoServiceImpl extends ServiceImpl<CpInfo, Long> implements ICpInfoService {

	@Autowired
	private ICpInfoDao cpInfoDao;

	/**
	 * 用的时候自己实现逻辑删除
	 * @param id id
	 * @return 版权所属信息
	 */
	@Override
	public CpInfo deleteLogic(Long id) {
		return null;
	}

	/**
	 * 更新对象
	 * @param model 要更新的对象
	 * @return 返回更新后的对象
	 */
	@Override
	public CpInfo merge(CpInfo model) {
		return null;
	}

	/**
	 * 分页查询
	 * @param cpInfo 查询条件
	 * @param page 页码
	 * @param rows 条数
	 * @param sidx 排序列
	 * @param sord 升序/降序
	 * @return 分页查询结果
	 */
	public Page<CpInfo> findAll(CpInfo cpInfo,int page, int rows, String sidx, String sord){
		//构造查询条件
		Specification<CpInfo> specification = getWhereClause(cpInfo);
		//构造分页信息
		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);
		Pageable pageable = PageRequest.of(page - 1, rows, sort);

		return cpInfoDao.findAll(specification,pageable);
	}

	/**
	 * 不分页查询
	 * @param cpInfo 查询条件
	 * @param sidx 排序列
	 * @param sord 升序/降序
	 * @return 查询结果
	 */
	public List<CpInfo> findAll(CpInfo cpInfo,String sidx, String sord){
		Specification<CpInfo> specification = getWhereClause(cpInfo);

		Sort sort = new Sort("desc".toLowerCase().equals(sord) ?
				Sort.Direction.DESC : Sort.Direction.ASC, sidx);

		return cpInfoDao.findAll(specification,sort);
	}

	@Override
	@Transactional
	public int deleteByIds(List<Long> ids) {
		return cpInfoDao.deleteCpInfoByIds(ids);
	}

	private Specification<CpInfo> getWhereClause(final CpInfo cpInfo){
		return (Specification<CpInfo>)(r, q, cb) -> {
			List<Predicate> predicates = new ArrayList<>();
			//id输入精确匹配
			if (cpInfo.getCpId() != null) {
				predicates.add(cb.equal(r.get("cpId"), cpInfo.getCpId()));
			}
			//name输入模糊匹配
			if (cpInfo.getCpName() != null) {
				predicates.add(cb.like(r.get("cpName"), "%"+cpInfo.getCpName()+"%"));
			}
			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		};
	}
}
